﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace XiTi
{
    public class PaperManagerHelper
    {
        private string baseDir;
        private static PaperManagerHelper helper;
        private List<PaperItem> papers;
        private string listFile;

        public static Encoding utf8 = new UTF8Encoding(false);

        private PaperManagerHelper()
        {
            baseDir = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "papers");
            if (!Directory.Exists(baseDir))
            {
                Directory.CreateDirectory(baseDir);
            }
            listFile = Path.Combine(baseDir, "list.json");
            if(File.Exists(listFile))
            {
                papers = JsonConvert.DeserializeObject<List<PaperItem>>(File.ReadAllText(listFile, utf8));
            }
            else
            {
                papers = new List<PaperItem>();
            }
        }

        public void savePaperList()
        {
            File.WriteAllText(listFile, JsonConvert.SerializeObject(papers), utf8);
        }

        public List<PaperItem> getPaperList()
        {
            return papers;
        }

        public void deletePaper(PaperItem paper)
        {
            papers.Remove(paper);
            savePaperList();
        }

        public static PaperManagerHelper Take()
        {
            if(helper== null)
            {
                helper = new PaperManagerHelper();
            }
            return helper;
        }

        public string getPaperDir(string pid)
        {
            string paperDir = Path.Combine(baseDir, pid);
            if (!Directory.Exists(paperDir))
            {
                Directory.CreateDirectory(paperDir);
            }
            return paperDir;
        }

        public string getPaperJsonFile(string pid)
        {
            return Path.Combine(getPaperDir(pid), "paper.json");
        }

        public PaperItem savePaper(Paper paper)
        {
            string fn = getPaperJsonFile(paper._meta.pid);
            File.WriteAllText(fn, JsonConvert.SerializeObject(paper), utf8);

            PaperItem item = new PaperItem();
            item.id = paper._meta.pid;
            item.name = paper._meta.title;

            papers.Add(item);
            savePaperList();
            return item;
        }
    }
}
